﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAbstractor;
using DataAbstractorExample.Forms;
using DataAbstractorExample.Models;

namespace DataAbstractorExample.Controllers
{
    public class NoteController : Controller
    {
        public ActionResult Index()
        {
            var context = new DataContext();
            var notes = context.Notes.Include("Comments").ToArray().Select(i => 
                {
                    return i.To<NoteView>();
                });
            ViewBag.Notes = new NoteListView { Notes = notes }; 
            return View(new CommentAdd());
        }

        public ActionResult Add()
        {
            return View(new NoteEdit());
        }

        [HttpPost]
        public ActionResult Add(NoteEdit model)
        {
            var context = new DataContext();
            context.Notes.Add(model.To<Note>());
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id)
        {
            var context = new DataContext();
            var note = context.Notes.FirstOrDefault(i => i.NoteId == id);
            if (note == null) return RedirectToAction("Index");
            return View(note.To<NoteEdit>());
        }

        [HttpPost]
        public ActionResult Edit(int id, NoteEdit model)
        {
            var context = new DataContext();
            var note = context.Notes.FirstOrDefault(i => i.NoteId == id);
            if (note == null) return RedirectToAction("Index");
            note.ShallowCopyFrom(model);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Remove(int id)
        {
            var context = new DataContext();
            var note = context.Notes.FirstOrDefault(i => i.NoteId == id);
            if (note != null)
            {
                context.Notes.Remove(note);
                context.SaveChanges();
            }

            return RedirectToAction("Index");
        }
    }
}
